import jsonexport from 'jsonexport/dist';
import { saveAs } from 'file-saver';

export const exportDataToCSV = async (exportDatas: any[], columns: any[]) => {
  const useData: any[] = exportDatas.map((data) => {
    const result = {};
    columns.forEach((item) => {
      const { dataIndex, title, hideInTable, allowExport } = item;
      if (data.hasOwnProperty(dataIndex as string) && (!hideInTable || allowExport)) {
        result[title as string] = data[dataIndex as string];
      }
    });
    return result;
  });
  if (useData.length > 20000) {
    //数据切片，每20000条一组进行转换，否则会导致浏览器卡死
    const sliceCount = Math.ceil(useData.length / 20000);
    const sliceData: any[] = [];
    for (let i = 0; i < sliceCount; i++) {
      sliceData.push(useData.slice(i * 20000, (i + 1) * 20000));
    }
    let csv = '';
    for (let i = 0; i < sliceData.length; i++) {
      csv += await jsonexport(sliceData[i]);
    }
    const blob = new Blob([csv ? '\ufeff' + csv : csv], {
      type: 'text/csv;charset=utf-8;',
    });
    saveAs(blob, 'data.csv');
  } else {
    const csv = await jsonexport(useData || []);
    const blob = new Blob([csv ? '\ufeff' + csv : csv], {
      type: 'text/csv;charset=utf-8;',
    });
    saveAs(blob, 'data.csv');
  }
};

//复制到剪贴板
export const copyToClipboard = (value: string) => {
  if (navigator.clipboard) {
    // clipboard api 复制
    navigator.clipboard.writeText(value);
  } else {
    // document.execCommand 复制
    const copyEl = document.createElement('input');
    copyEl.setAttribute('value', value);
    document.body.appendChild(copyEl);
    copyEl.select();
    document.execCommand('copy');
    document.body.removeChild(copyEl);
  }
};

// Number类型保留指定小数，返回字符串
export const formatNumber = (num: number, decimal: number = 0) => {
  const number = Number(num);
  if (isNaN(number) || number === 0 || number === Infinity || number === -Infinity) {
    if (decimal === 0) return '0';
    return '0.' + '0'.repeat(decimal);
  } else {
    return number.toLocaleString(undefined, {
      minimumFractionDigits: decimal,
      maximumFractionDigits: decimal,
    });
  }
};

export const compare = (a: any, b: any, fieldName: string, isNumber?: boolean) => {
  const transformDataFormat = (data: any) => {
    if (isNumber || !Number.isNaN(Number(data[fieldName]))) {
      return Number(data[fieldName]);
    } else {
      return data[fieldName];
    }
  };
  const aVal = transformDataFormat(a);
  const bVal = transformDataFormat(b);
  if (aVal == bVal) {
    return 0;
  }
  return aVal > bVal ? 1 : -1;
};

export const destroyTooltipElementOnHide = () => {
  try {
    setTimeout(() => {
      const tooltipElements = document.querySelectorAll('.ant-tooltip');
      tooltipElements.forEach((element) => {
        element.classList.add('ant-tooltip-hidden');
      });
    }, 500);
  } catch (error) {}
};